$(function() {
    let flagName     = false;
    let flagPassword = false;
    let flagCaptcha  = false;

    // 验证用户名
    $('#username').change(function() {
        let name = $('#username').val().trim();
        if (getStringLength(name) < 3) {
            $('#username').addClass('is-invalid');
            $('#nameHelp').text('请输入 3~16 位的用户名').addClass('red');
            flagName = false;
        } else {
            $('#username').removeClass('is-invalid');
            $('#nameHelp').text('用户名').removeClass('red');
            flagName = true;
        }
    });
    // 验证密码
    $('#password').change(function() {
        let password = $('#password').val().trim();
        if (password.length < 6) {
            $('#password').addClass('is-invalid');
            $('#passwordHelp').text('密码至少 6 位数').addClass('red');
            flagPassword = false;
        } else {
            $('#password').removeClass('is-invalid');
            $('#passwordHelp').text('密码').removeClass('red');
            flagPassword = true;
        }
    });
    // 验证验证码
    $('#captcha').change(function() {
        captcha = $('#captcha').val().trim();
        if (captcha.length < 4) {
            $('#captcha').addClass('is-invalid');
            $('#captchaHelp').text('请输入 4 位数的验证码').addClass('red');
            flagcaptcha = false;
        } else {
            $('#captcha').removeClass('is-invalid');
            $('#captchaHelp').text('验证码').removeClass('red');
            flagCaptcha = true;
        }
    });

    // 点击注册按钮后验证
    $('#submitButton').click(function() {
        if (!flagName) {
            $('#username').addClass('is-invalid').focus();
            $('#nameHelp').text('请输入 3~16 位的用户名');
            return;
        }
        if (!flagPassword) {
            $('#password').addClass('is-invalid').focus();
            $('#passwordHelp').text('密码至少 6 位数');
            return;
        }
        if (!flagCaptcha) {
            $('#captcha').addClass('is-invalid').focus();
            $('#captchaHelp').text('请输入 4 位数的验证码');
            return;
        }

        let data = new FormData(document.getElementById('auth-form'));
        ajax('/user/register/submit', data, function(res) {
            if (res.status === 'success') {
                toast.success(res.message, 3000);
                setTimeout(function() {
                    document.referrer === "" ? (window.location.href = "/") : window.history.back();
                }, 1500);
            } else {
                toast.error(res.message, 3000);
                $(".auth-captcha").attr("src", "/user/captcha/" + Math.random());
            }
        });
    });
});